let app = getApp();
import {
  getPersonAuth,
  realPersonAuth,
  checkPersonAuth,
  createPreAuth,
  createContract,
  grantAuthMobile,
  createHuabei,
  createAntchain
} from "../../api/index";
import { uploadImg } from "../../utils/request";

import { checkName, validateIdCard } from "../../utils/validate";
import { disposeData, backMini } from "../../utils/outData";
const esignPlugin = requirePlugin("esign");
Page({
  data: {
    userName: '',
    userIdcard: '',
    card_front: '',
    card_back: '',
    frontCard: [],
    backCard: [],
    orderId: '',
    payType: '',
    contractType: '',  //合同类型  1蚂蚁智能合同  2E签宝合同
    // signNum: '',       //签署方数量   2两方  3三方
    isReady: false,
    isAuth: '',
    orderStatus: '',
    esignFlowId: '',
    esignUserId: '',
    cradName:'',
    cradId:'',
    gooddsId:'',
    setmealId:'',
    spectId:'',
    amount:'',
    activityId:'',
    authStatus:'',
    checkAuth:'',
    flag:'',
    array:['父母','配偶','兄弟','姐妹','亲戚','姐妹','朋友','同事'],
    idInfo:[],
    relation:'',
    relationName:'',
    relationPhone:'',
    authPhone:'',
    email:''
  },
  onLoad(option) {
    my.removeStorage({ key: 'hasCreateSign' });
    my.removeStorage({ key: 'authStatus' });
    const { orderId, payType, esignUserId, flowId, isAuth, status, contractType } = option
    this.setData({
      orderId,
      payType,
      isAuth,
      orderStatus: status,
      esignFlowId: flowId,
      esignUserId,
      contractType,
      cradId:option.cradId,
      cradName:option.cradName,
      gooddsId:option.goodsId,
      setmealId:option.setmealId,
      spectId:option.specId,
      amount:option.amount,
      activityId:option.activityId,
      flag:option.beforeAuth
    })
    console.log(option);
    getPersonAuth().then(res => {
      this.setData({
        userName: res.certName,
        userIdcard: res.certNo,
        card_front: res.cardFront,
        card_back: res.cardBack,
        checkAuth:res.is_auth
      })
    })
  },
  onShow() {
    setTimeout(() => { my.hideLoading() }, 500);
    let hasCreateSign = my.getStorageSync({ key: 'hasCreateSign' }).data;
    if (hasCreateSign) {
      const { code } = esignPlugin.getSignStatusInfo();
      if (code == '000') {
        my.showLoading({ content: '跳转中...' });
        setTimeout(() => { my.hideLoading() }, 1500);
        my.reLaunch({
          url: '/pagesA/pages/paySuccess/paySuccess?orderId=' + this.data.orderId
        })
      }
    }
    const authPhone = my.getStorageSync({ key: 'authPhone' }).data;

    let relationInfo = my.getStorageSync({ key: 'relationInfo' }).data;
    this.setData({
      authPhone
    })
    if(relationInfo){
      this.setData({
        relation:relationInfo.relation,
        relationName:relationInfo.relationName,
        relationPhone:relationInfo.relationPhone,
        email:relationInfo.email,
      })
   }
 
  },
  bindPickerChange(e) {
    this.setData({index:e.detail.value});
    this.setData({relation:this.data.array[e.detail.value]});
    // this.getArrList()
  },    
  relationPhone(e) {
    this.setData({ relationPhone: e.detail.value })
  },
  relationName(e) {
    this.setData({ relationName: e.detail.value })
  },
  onName(e) {
    this.setData({ userName: e.detail.value })
  },
  onEmail(e) {
    this.setData({ email: e.detail.value })
  },
  onIdcard(e) {
    this.setData({ userIdcard: e.detail.value })
  },
  uploadPhoto(e) {
    if(this.data.checkAuth=='1'){
      my.showToast({
        type: 'fail',
        content: '您已经完成实名认证,不可以再次修改证件照片！',
        duration: 2000,
      });
    }else{
      const that = this;
    let cardId = e.currentTarget.dataset.id
    let list = []
    if (cardId == 1) {
      uploadImg(function (url) {
        if (url) {
          list.push(url);
          that.setData({
            frontCard: list,
            card_front: list[0]
          })
        }
      });
    } else {
      uploadImg(function (url) {
        if (url) {
          list.push(url);
          that.setData({
            backCard: list,
            card_back: list[0]
          })
        }
      });
    }
    }
    
  },
  getAuthPhone() {
    const token = my.getStorageSync({ key: 'token' }).data;
    if (!token) {
      app.getAuthUser(function (res) {
        if (res) {
          this.getPhone()
        }
      })
    } else {
      this.getPhone()
    }
  },
  getPhone() {
    const that = this
    my.getPhoneNumber({
      success: (res) => {
        let encryptedData = JSON.parse(res.response).response;
        grantAuthMobile(encryptedData).then(res => {
          if (res) {
            my.setStorage({ key: 'authPhone', data: res.mobile })
            that.setData({ authPhone: res.mobile })
            my.showToast({
              type: 'success',
              content: '获取手机号成功',
            })
            // this.submitOrder()
          } else {
            my.showToast({
              type: 'fail',
              content: '获取手机号失败,请稍后重试',
              duration: 1500,
            })
          }
        })
      },
    });
  },
  // e签宝
  isContract() {
    const that = this
    const { orderId, esignFlowId, esignUserId } = that.data
    const env = 'prod'
    if ((esignFlowId && esignFlowId != 0 && esignFlowId != 'null') && esignUserId) {
      my.setStorage({ key: 'hasCreateSign', data: true });
      my.showLoading({ content: '正在跳转合同...' });
      setTimeout(() => { my.hideLoading() }, 800);
      my.navigateTo({
        url: `plugin://esign/esign?env=${env}&flowId=${esignFlowId}&signerId=${esignUserId}`,
      })
    } else {
      my.showLoading({ content: '正在跳转合同...' });
      createContract(orderId).then(res => {
        if (res.flowId) {
          my.hideLoading({ page: that });
          my.setStorage({ key: 'hasCreateSign', data: true });
          const { flowId, signerId } = res
          my.navigateTo({
            url: `plugin://esign/esign?env=${env}&flowId=${flowId}&signerId=${signerId}`,
          })
        }
      })
    }
  },
  // 预授权
  createAuth() {
    const that = this;
    const { orderId, payType } = that.data
    if (payType == 2 || payType==1) {
      createPreAuth(orderId).then(res => {
        if (res.orderStr) {
          my.tradePay({
            orderStr: res.orderStr,
            success: (res) => {
              if (res.resultCode == 9000) {
                my.reLaunch({ url: '../../packageB/pages/paySuccess/paySuccess?orderId=' + orderId })
              } else {
                if(payType == 2){
                  my.confirm({
                    title: '提示',
                    content: '押金过高？试试申请押金减免',
                    confirmButtonText: '是,申请',
                    cancelButtonText: '否',
                    success: res => {
                      if (res.confirm) {
                        my.redirectTo({ url: '../../packageA/pages/myOrder/myOrder?order_status='+0 })
                      } else {
                          my.reLaunch({ url: '../user/orderpay/orderpay?id=' + orderId })
                      }
                    },
                  });
                }
              }
            },
            fail: (res) => {
              my.showToast({
                type: 'fail',
                content: '支付失败，请稍后重试',
                duration: 1000,
              });
            }
          });
        } else {
          my.reLaunch({
            url: '../../packageB/pages/paySuccess/paySuccess?orderId=' + orderId
          })
        }
      })
    } else if (payType == 3) {
      createHuabei(orderId).then(res => {
        if (res.trade_no) {
          my.tradePay({
            tradeNO: res.trade_no,
            success: (res) => {
              let data = JSON.parse(JSON.stringify(res))
              if (data.resultCode == 9000) {
                my.reLaunch({
                  url: '../../packageB/pages/paySuccess/paySuccess?orderId=' + orderId
                })
              } else {
                my.showToast({
                  type: 'fail',
                  content: '支付失败，请稍后重试',
                  duration: 1000,
                });
              }
            }
          });
        } else {
          if (res.sign_status == 0) {
            that.isContract()
          } else if (res.sign_status == 1) {
            my.confirm({
              title: '提示',
              content: '继续签署合同?',
              confirmButtonText: '是,继续',
              cancelButtonText: '否,回首页',
              success: info => {
                if (info.confirm) {
                  my.showLoading({ content: '正在跳转合同...' });
                  setTimeout(() => { my.hideLoading() }, 800);
                  my.setStorage({ key: 'hasCreateSign', data: true });
                  my.navigateTo({
                    url: `plugin://esign/esign?env=${'prod'}&flowId=${res.flow_id}&signerId=${res.esign_user_id}`,
                  })
                } else {
                  my.switchTab({ url: '/pages/index/index' })
                }
              },
            });
          }else if(payType == 1){

          } else {
            my.showLoading({ content: '合同已签署完成...' });
            setTimeout(() => { my.hideLoading() }, 1000);
            my.switchTab({ url: '/pages/index/index' })
          }
        }
      })
    }
  },
  toAuth() {
    const that = this
    const { userName, userIdcard, card_front, card_back, orderStatus, contractType, orderId, gooddsId,email } = that.data
    if (!userName || !userIdcard) {
      my.showToast({
        type: 'none',
        duration: 1500,
        content: '个人信息不能为空'
      });
      return
    } else if (!card_front || !card_back) {
      my.showToast({
        type: 'none',
        duration: 1500,
        content: '证件照不能为空'
      });
      return
    }
    if (userName && !checkName(userName)) {
      return;
    }

    if (!that.data.relation) {
      my.showToast({
        type: 'none',
        duration: 1500,
        content: '请选择紧急联系人'
      });
      return
    }
      if (!that.data.relationName) {
      my.showToast({
        content: "联系人姓名不能为空",
        type: 'fail',
        duration: 1000
      });
      return false;
    }
    const nameReg = /^[a-zA-Z\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/;
    if (!nameReg.test(that.data.relationName)) {
      my.showToast({
        content: "联系人姓名格式输入错误",
        type: 'fail',
        duration: 3000
      });
      return false;
    }

    let phone=that.data.relationPhone;
    if (!phone) {
      my.showToast({
        content: '请输入联系人手机号',
        type: 'fail',
        duration: 1000
      })
      return false
    }
    if (phone.length < 11) {
      my.showToast({
        content: '联系人手机号位数不对，请重新输入',
        type: 'fail',
        duration: 1000
      })
      return false
    }
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
      my.showToast({
        content: '联系人手机号格式有误，请重新输入',
        type: 'fail',
        duration: 1000
      })
      return false
    }
    if (!this.data.email) {
      my.alert({ content: '请输入邮箱' });
      return;
    }
    const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    if (email && !(reg.test(email))) {
      my.showToast({
        content: '邮箱格式有误，请重新输入',
        type: 'fail',
        duration: 1000
      })
      return
    }

    my.setStorageSync({
      key: 'relationInfo',
      data: {
        relation: that.data.relation,
        relationName: that.data.relationName,
        relationPhone: that.data.relationPhone,
        email: that.data.email
      },
    });

    console.log(this.data.orderId);
    realPersonAuth({
      orderId:this.data.orderId,
      certName: userName,
      certNo: userIdcard,
      cardFront: card_front,
      cardBack: card_back,
      gooddsId
    }).then(res => {
      if (res.certify_id) {
        my.startAPVerify({
          url: res.certify_url,
          certifyId: res.certify_id,
          success: function (info) {
            checkPersonAuth(res.certify_id).then(result=>{
              console.log(1112);
              if (info.resultStatus == 9000) {
                  my.showLoading({
                    content: '加载中...',
                    complete:(res=>{
                      setTimeout(() => {
                        my.hideLoading();
                      }, 2000);
                    })
                  });
                  console.log(111);
                  my.navigateBack(); 
              }
            })
          }
        })
      }else{
        my.showToast({
                        type: 'fail',
                        content: '认证失败，请稍后重试',
                        duration: 1000,
               });
      }
    })
  },
  submitBtn(){
    this.toAuth();
  }
});